<?php
// +----------------------------------------------------------------------
// | title: 发系统邮件计划任务，每5分钟启动一次
// +----------------------------------------------------------------------
// | Author: join
// +----------------------------------------------------------------------
// | Date: 2016-03-22 14:25
// +----------------------------------------------------------------------
// | Run: php index.php Content/SingleTask/SysMail bzsc Single mail_id=0#debug=1
// +----------------------------------------------------------------------

namespace app\single\command;

use app\single\model\MailModel;
use app\single\model\RoleMailModel;
use app\single\model\RoleModel;
use think\Command;
use think\facade\Log;
use think\facade\Cache;

class SysMail extends Command
{
    protected function execute($input, $output)
    {
        $model = new MailModel();//系统邮件配置表
        $roleModel = new RoleModel();//玩家表
        $roleMailModel = new RoleMailModel();//玩家邮件表
        $sendNumPerTime = 100;//发送多少条停一下
        //查询邮件数据
        $data = $model->where("status", 0)->where("send_time", "<=", time())->select()->toArray();
        if (empty($data)) {
            echo "mail列表空的" . PHP_EOL;
            exit;
        }
        $serverInfo= Cache::store("file")->get("server_info");
        $opentime = $serverInfo["create_time"]; 
        $currentDay = (int) ceil((time() - $opentime) / 86400);

        //        echo "data".json_encode($data,true).__LINE__.PHP_EOL;
        //开始处理邮件数据
        foreach ($data as $vo) {
            //主键ID

            $id = $vo["id"] ?? 0;

            //            echo "222222====>vo=>".$id."=====".__LINE__.PHP_EOL;
            //更新状态为发送中
            if (false === $model->updateStatus($id, array("status" => 1))) {
                //更新失败，不发送这条邮件
                echo "更新失败 不发送" . PHP_EOL;
                continue;
            }
            //            echo "33333".__LINE__.PHP_EOL;
            $condition = json_decode($vo["condition"], true);
            //获取要发送的玩家ID和玩家name
            $playerArr = array();

            $target = (int) $condition["target"];
            $mailKind = 1;
            switch ($target) {
                case 1:
                    $map = array();
                    //平台号
                    //todo:需要后续开启
                    
                   $openday =(int) $condition["info"]["open_days"] ??0;
                   if($openday){
                       if($currentDay<$openday ||time()<$opentime){
                            //未到开服天数 不发
                            continue;
                       }
                   }

                   $platform = $condition["info"]["pf"] ?? "";
                   if ($platform) {
                       $map["a.pf"] = $platform;
                   }
//                    //职业
////                if(!empty($condition["info"]["career"])){
////                    $map["career"] = array("in",$condition["info"]["career"]);
////                }
//                    //玩家等级
                    $map["a.lev"] = array("between", array($condition["info"]["min_level"], $condition["info"]["max_level"]));
                    //                    //玩家转生等级
////                $map["round"] = array("between",array($condition["info"]["min_rinne"],$condition["info"]["max_rinne"]));
//                    //最近登录天数
                    if ($condition["info"]["last_days"] > 0) {
                        $map["a.last_login_time"] = array("EGT", strtotime("-{$condition["info"]["last_days"]} days"));
                    }
                    //                    //是否付费玩家
                    if ($condition["info"]["is_pay"] > 0) {
                        $map["a.charge"] = array("GT", 0);
                        //                        $map["c.level"] = array("between", array($condition["info"]["min_vip"], $condition["info"]["max_vip"]));
                    }
                    $playerInfo = $roleModel->getMailPlayerInfo($map);
                    var_dump($playerInfo);
                    if ($playerInfo) {
                        foreach ($playerInfo as $kv) {
                            $playerArr[] = array(
                                "player_id" => $kv["id"],
                                "name" => $kv["name"],
                            );
                        }
                    }
                    //                    echo "debug mail user" .var_export($playerArr,true).__LINE__.PHP_EOL;
                    break;
                case 2:
                    foreach ($condition["info"] as $k => $name) {
                        $playerInfo = $roleModel->where(array("name" => $name, ))->field("id,name")->find();
                        //                        print  "debug last query sql" . $roleModel->getLastSql();
                        if ($playerInfo) {
                            $playerArr[] = array(
                                "player_id" => $playerInfo["id"],
                                "name" => $playerInfo["name"],
                            );
                        }
                    }
                    break;
                case 3:
                    foreach ($condition["info"] as $k => $roleId) {
                        $playerInfo = $roleModel->where(array("id" => $roleId))->field("id,name")->find();
                        if ($playerInfo) {
                            $playerArr[] = array(
                                "player_id" => $playerInfo["id"],
                                "name" => $playerInfo["name"],
                            );
                        }
                    }
                    ;
                    break;
                default:
                    break;
            }

            $attachment = "";
            if (!empty($vo["attachment"])) {
                $itemArr = json_decode($vo["attachment"], true);
                $attachment = newattachment($itemArr);
            } else {
                $attachment = '[]';
            }

            $mail_type = $vo["mail_type"] ?? 1;
            //按条件群发
            if ($target == 4) {
                $playerId = 1;
                $mail_data = [
                    "mail_kind" => 3,
                    'type' => $mail_type,
                    'send_time' => time(),
                    "expire_time" => time() + 86400 * 30,
                    'to_rid' => (int) $playerId,
                    "title" => string2ascii($vo["title"] ?? ""),
                    "content" => string2ascii($vo["content"] ?? ""),
                    "item" => $attachment
                ];

                $serdata = [
                    (int) $mail_data["mail_kind"],
                    (int) $mail_data["type"],
                    (int) $mail_data["send_time"],
                    (int) $mail_data["expire_time"],
                    (int) $mail_data["to_rid"],
                    $mail_data["title"],
                    $mail_data["content"],
                    $mail_data["item"]
                ];
                var_dump($serdata);
                echo ("debug  request server_data" . json_encode($serdata)) . PHP_EOL;
                $res = $this->newSendMail($serdata);
                if ($res && $res["code"] == BACKGROUND_SUCCESS) {
                    //插入邮件表，获取邮件表主键ID
                    $roleMailModel->sendMail($playerId, $attachment, $vo["title"], $vo["content"], $mail_type);
                } else {
                    $model->updateStatus($id, array("status" => 0));
                    exit("连接游戏服失败，请重试");
                }

            } else {
                //获取邮件附件

                //开始发邮件了
                $i = 0;
                $operate = "";//操作在线表json字段

                foreach ($playerArr as $info) {
                    $i++;
                    $playerId = $info["player_id"];



                    //拿不到主键ID，程序可能有问题了
                    $mail_data = [
                        "mail_kind" => $mailKind,
                        'type' => $mail_type,
                        'send_time' => time(),
                        "expire_time" => time() + 86400 * 30,
                        'to_rid' => (int) $playerId,
                        "title" => string2ascii($vo["title"] ?? ""),
                        "content" => string2ascii($vo["content"] ?? ""),
                        "item" => $attachment
                    ];

                    $serdata = [
                        (int) $mail_data["mail_kind"],
                        (int) $mail_data["type"],
                        (int) $mail_data["send_time"],
                        (int) $mail_data["expire_time"],
                        (int) $mail_data["to_rid"],
                        $mail_data["title"],
                        $mail_data["content"],
                        $mail_data["item"]
                    ];
                    echo ("debug  request server_data" . json_encode($serdata)) . PHP_EOL;
                    $res = $this->newSendMail($serdata);
                    if ($res && $res["code"] == BACKGROUND_SUCCESS) {
                        //插入邮件表，获取邮件表主键ID
                        $roleMailModel->sendMail($playerId, $attachment, $vo["title"], $vo["content"], $mail_type);
                    } else {
                        $model->updateStatus($id, array("status" => 0));
                        exit("连接游戏服失败，请重试");
                    }
                }
            }

            //更新邮件总数
            $model->updateStatus($id, array("player_num" => count($playerArr)));

        }

        //发成功了
        $model->updateStatus($id, array("status" => 2));
    }

    /**
     * @param string $operate 邮件表主键ID列表
     * @return bool
     */
    private function addOperate(&$operate): bool
    {
        //没东西直接退出
        if (empty($operate)) {
            return false;
        }
        //插入在线操作接口表
        $operate = '[' . rtrim($operate, ",") . ']';
        PHP2Erlang(BACKGROUND_MAIL, array(), $operate);
        $operate = "";
        return true;
    }


    public function newSendMail(array $mail_data)
    {
        $res = PHP2Erlang(BACKGROUND_MAIL, $mail_data);
        return $res;
    }
}